import { Form, Row, Col, Input, Button, Select, Table, DatePicker, Checkbox } from 'antd';
import React, { useState, Fragment, useEffect } from 'react';
import IndemnityCountTable from '../../IndemnityCountTable/index';
import { useBoolean, useRequest } from '@umijs/hooks';
import style from '../styles.less';
import { getCompensationCount } from '../../../service';
import moment from 'moment';
const AddPassenger = props => {
    const { form: { getFieldDecorator, getFieldsValue, resetFields },
        handleModalVisible,
        handleTable,
        passengerDataTable,
        handelCheckedList,
        checkedPassengerList,
        flightInfo,
        queryPassengerMaintenance,
        handlePageSize,
        handleCurrent,
        handleTotal,
        segmentData
    } = props;
    const [createModalVisible, handleModalCount] = useState(false);
    // 存储全部旅客
    const [allPassengers, saveAllPassengers] = useState(passengerDataTable);

    // 表格选中项
    const [tableSelected, handleSelected] = useState(checkedPassengerList);

    // 点击的旅客姓名储存
    const [passengerName, handlePassengerName] = useState('');

    // 航段下拉框数据
    const [hDSelect = []] = useState([' '].concat(flightInfo.choiceSegment.split(',')));

    // 获取补偿次数表格数据
    const { data: countData, run } = useRequest((params) => getCompensationCount(params));
    // 点击全部或者选中旅客 全部-false 选中旅客-true
    const { state: selectState, setTrue, setFalse } = useBoolean(false);

    const [disabledFlightStartDate, setDisabledFlightStartDate] = useState('')
    const [disabledFlightEndDate, setDisabledFlightEndDate] = useState('')
    const [checkedMans, setCheckedMans] = useState(0)// 已选旅客人数（包含婴儿）
    const [allMans, setAllMans] = useState(0)// 全部旅客人数（包含婴儿）
    const [selectedRowKeys, setSelectedRowKeys] = useState([])// 选中项的id

    const [segments, setSegments] = useState([])// 航段数据
    const [defaultSelectVal, setDefaultSelectVal] = useState("all")// 航段数据

    //   const [disabledSendStartTime, setDisabledSendStartTime] = useState('')
    //   const [disabledSendEndTime, setDisabledSendEndTime] = useState('')

    useEffect(() => {

        if (segmentData.cCode) { //存在经停
            if (flightInfo.orig === segmentData.aCode) { // 前半段
                setSegments([
                    { lable: "全部", value: "all_before" },
                    { lable: `${segmentData.aName}-${segmentData.bName}`, value: "before" },
                    { lable: `${segmentData.aName}-${segmentData.cName}`, value: "ac" }
                ]);
                setDefaultSelectVal("all_before");
            }
            if (flightInfo.orig === segmentData.bCode) { // 后半段
                setSegments([
                    { lable: "全部", value: "all_after" },
                    { lable: `${segmentData.bName}-${segmentData.cName}`, value: "after" },
                    { lable: `${segmentData.aName}-${segmentData.cName}`, value: "ac" }
                ]);
                setDefaultSelectVal("all_after");
            }
        } else { //不存在经停
            setSegments([
                { lable: "全部", value: "all" },
                { lable: flightInfo.choiceSegment, value: "all_b_a" }
            ]);
            setDefaultSelectVal("all");
        }
    }, [segmentData, flightInfo])


    useEffect(() => {
        let checkArr = [];
        if (selectState) {
            saveAllPassengers(tableSelected);
        } else {
            saveAllPassengers(passengerDataTable);
        }
        let mans = 0; //所有计算人数
        for (let item of passengerDataTable) {
            if (item.withBaby === 'Y') {
                mans += 1;
            }
            // for (let iterator of tableSelected) {
            //     if(iterator.idx === item.idx){
            //         checkArr.push(item.idx);
            //     }
            // }
        }
        setAllMans(mans + passengerDataTable.length);

        let selectMans = 0; //计算选中人数
        for (let item of tableSelected) {
            checkArr.push(item.idx);
            if (item.withBaby === 'Y') {
                selectMans += 1;
            }
        }
        setSelectedRowKeys(checkArr);
        setCheckedMans(selectMans + tableSelected.length);
        handleSelected(tableSelected);
        // }, [passengerDataTable,tableSelected])
    }, [passengerDataTable, tableSelected])

    // 打开总补偿次数
    const openCountModal = (payCount, record) => {
        if (payCount === '0') {
            return false;
        }
        handleModalCount(true);
        handlePassengerName(record.psgName)
        run({
            flightNo: record.flightNum,
            flightDate: record.flightDate,
            paxId: record.idx
        })
    };
    const formItemLayout = {
        labelCol: {
            md: { span: 6 }
        },
        wrapperCol: {
            md: { span: 16 }
        },
    };

    const columns = [
        {
            title: '姓名',
            dataIndex: 'psgName',
            fixed: 'left',
            width: 100,
            align: 'center',
            render: (text, record) => {
                return (
                    <div>
                        <span style={{ verticalAlign: 'middle' }}>{text}</span>
                        {record.withBaby === "Y" ? (<img alt="" style={{ verticalAlign: 'middle' }} src={require('../../../components/images/icon-test.svg')} />) : null}
                        {record.isChild === "Y" ? (<img alt="" style={{ verticalAlign: 'middle' }} src={require('../../../components/images/ertong.svg')} />) : null}
                    </div>
                )
            }
        },
        {
            title: '证件类型',
            dataIndex: 'idType',
            fixed: 'left',
            width: 110,
            align: 'center',
            render: idType => (
                <span>{idType === '1' ? '身份证' : '其他'}</span>
            )
        },
        {
            title: '证件号',
            dataIndex: 'idNum',
            fixed: 'left',
            width: 180,
            align: 'center'
        },
        {
            title: '购票时间',
            dataIndex: 'printTicketTime',
            fixed: 'left',
            width: 170,
            align: 'center'
        },
        {
            title: '旅客手机号',
            ellipsis: true,
            dataIndex: 'phone',
            align: 'center',
            width: 120
        },
        {
            title: '航段',
            dataIndex: 'segment',
            width: 140,
            align: 'center'
        },
        {
            title: '总补偿次数',
            dataIndex: 'payCount',
            width: 100,
            align: 'center',
            render: (payCount, record) => (
                <span onClick={() => {
                    openCountModal(payCount, record)
                }} className={payCount !== '0' ? style.count : ''}>{payCount}</span>
            )
        },
        {
            title: '总补偿金额',
            dataIndex: 'payMoney',
            width: 100,
            align: 'center'
        },
        {
            title: '值机状态',
            dataIndex: 'status',
            align: 'center',
            width: 130,
            render: (status) => (
                <>
                    <span style={{ display: status === 'PT' ? 'block' : 'none' }}>PT（出票）</span>
                    <span style={{ display: status === 'NA' ? 'block' : 'none' }}>NA（未值机）</span>
                    <span style={{ display: status === 'AC' ? 'block' : 'none' }}>AC（值机）</span>
                    <span style={{ display: status === 'XR' ? 'block' : 'none' }}>XR（值机取消）</span>
                    <span style={{ display: status === 'CL' ? 'block' : 'none' }}>CL（订座取消）</span>
                    <span style={{ display: status === 'SB' ? 'block' : 'none' }}>SB（候补）</span>
                    <span style={{ display: status === 'DL' ? 'block' : 'none' }}>DL（拉下）</span>
                </>
            )
        },
        {
            title: '是否取消',
            dataIndex: 'cancel',
            width: 90,
            align: 'center'
        },
        {
            title: '票号',
            dataIndex: 'etNum',
            width: 150,
            align: 'center'
        },
        {
            title: '主舱位',
            dataIndex: 'mainClass',
            width: 90,
            align: 'center'
        },
        {
            title: '子舱位',
            dataIndex: 'subClass',
            width: 90,
            align: 'center'
        },
        {
            title: 'PNR',
            dataIndex: 'pnr',
            align: 'center',
            width: 120
        },

    ];

    const submitData = () => {
        handleTable(true);
        handleModalVisible(false);
        let newObj = JSON.parse(JSON.stringify(tableSelected));
        newObj.forEach(v => {
            v['paxName'] = v.psgName
            v['idNo'] = v.idNum
            v['paxStatus'] = v.status
            v['tktNo'] = v.etNum
            v['subClass'] = v.subClass
            v['tktDate'] = v.printTicketTime
            v['paxId'] = v.idx
            v['orgCityAirp'] = v.orig
            v['dstCityAirp'] = v.dest
            v['telephone'] = v.phone
        })
        handlePageSize(10);
        handleCurrent(1);
        handleTotal(newObj.length);
        // debugger
        handelCheckedList(newObj);
    }
    const { Option } = Select
    // 选中项发生变化时的回调
    const rowSelection = (selectRowKeys, selectedRows) => {
        let mans = 0; //计算人数
        for (let item of selectedRows) {
            if (item.withBaby === 'Y') {
                mans += 1;
            }
        }
        setCheckedMans(mans + selectedRows.length);
    };
    // 用户手动选择/取消选择某行的回调
    const rowOnSelect = (record, selected, selectedRows, nativeEvent) => {
        let tempTableSelectIdx = JSON.parse(JSON.stringify(tableSelected))
        if (selected) { //勾选
            tempTableSelectIdx.push(record);
        } else { //取消
            for (let i = 0; i < tempTableSelectIdx.length; i++) {
                if (tempTableSelectIdx[i].idx === record.idx) {
                    tempTableSelectIdx.splice(i, 1);
                    continue;
                }
            }
        }
        let checkArr = [];
        for (let item of tempTableSelectIdx) {
            checkArr.push(item.idx);
        }
        setSelectedRowKeys(checkArr);
        handleSelected(tempTableSelectIdx);

        // console.log('手动选择/取消record', record);
        // console.log('手动选择/取消selected', selected);
        // console.log('手动选择/取消selec2222222222', selectedRows);
    }
    // 用户手动选择/取消选择所有行的回调
    const rowOnSelectAll = (selected, record, selectedRows) => {
        let tempTableSelectIdx = JSON.parse(JSON.stringify(tableSelected));
        if (tempTableSelectIdx.length === 0) {
            handleSelected(record);
        } else {
            if (selected) {
                for (const item of selectedRows) {
                    tempTableSelectIdx.push(item);
                }
                handleSelected(tempTableSelectIdx);
            } else {
                for (let i = 0; i < tempTableSelectIdx.length; i++) {
                    for (let j = 0; j < selectedRows.length; j++) {
                        if (tempTableSelectIdx[i] && tempTableSelectIdx[i].idx === selectedRows[j].idx) {
                            tempTableSelectIdx.splice(i, 1);
                        }
                    }
                }
            }
            handleSelected(tempTableSelectIdx);
        }
        let checkArr = [];
        for (let item of tempTableSelectIdx) {
            checkArr.push(item.idx);
        }
        setSelectedRowKeys(checkArr);


        // console.log('所有行record', record);
        // console.log('所有行selected', selected);
        // console.log('所有行selectedRows', selectedRows);
    }
    return (
        <Fragment>
            <Form {...formItemLayout} colon={false}>
                <Row gutter={16}>
                    <Col md={8}>
                        <Form.Item label="旅客搜索">
                            {getFieldDecorator('keySearch', {
                                initialValue: ""
                            })(
                                <Input placeholder="证件号/票号" />
                            )}
                        </Form.Item>
                    </Col>
                    <Col md={8}>
                        <Form.Item label="旅客姓名">
                            {getFieldDecorator('paxName', {
                                initialValue: ""
                            })(
                                <Input placeholder="请输入旅客姓名" />
                            )}
                        </Form.Item>
                    </Col>
                    <Col md={8}>
                        <Form.Item label="航段">
                            {getFieldDecorator('hd', {
                                initialValue: defaultSelectVal
                            })(
                                <Select placeholder="请选择航段">
                                    {segments && segments.map(v => (<Option key={v.lable} value={v.value}>{v.lable}</Option>))}
                                </Select>
                            )}
                        </Form.Item>
                    </Col>
                </Row>
                <Row gutter={16}>
                    <Col md={8}>
                        <Form.Item label="起始购票时间">
                            {getFieldDecorator('tktStartDate', {
                                initialValue: ''
                            })(
                                <DatePicker onChange={(value) => {
                                    setDisabledFlightStartDate(value)
                                }}
                                    disabledDate={(value) => {
                                        if (!disabledFlightEndDate || !value) {
                                            return false
                                        }
                                        // console.log(disabledFlightEndDate.valueOf());
                                        // console.log(moment(moment(disabledFlightEndDate).format('YYYY-MM-DD')).valueOf())
                                        // let temp = moment(moment(disabledFlightEndDate).format('YYYY-MM-DD')).valueOf()
                                        return value.valueOf() > (disabledFlightEndDate.valueOf())
                                    }}
                                    showTime={{ format: 'HH:mm' }} style={{ width: '100%' }} format="YYYY-MM-DD HH:mm" />
                            )}
                        </Form.Item>
                    </Col>
                    <Col md={8}>
                        <Form.Item label="结束购票时间">
                            {getFieldDecorator('tktEndDate', {
                                initialValue: ''
                            })(
                                <DatePicker onChange={(value) => {
                                    setDisabledFlightEndDate(value)
                                }}
                                    disabledDate={(value) => {
                                        if (!disabledFlightStartDate || !value) {
                                            return false
                                        }
                                        return value.valueOf() <= (disabledFlightStartDate.valueOf())
                                    }} showTime={{ format: 'HH:mm' }} style={{ width: '100%' }} format="YYYY-MM-DD HH:mm" />
                            )}
                        </Form.Item>
                    </Col>
                    <Col md={8}>
                        <Form.Item label="值机状态">
                            {getFieldDecorator('checkStatus', {
                                initialValue: ''
                            })(
                                <Select placeholder="请选择值机状态">
                                   <Option value="">全部</Option>
                                    <Option value="PT">PT（出票）</Option>
                                    <Option value="NA">NA（未值机）</Option>
                                    <Option value="AC">AC（值机）</Option>
                                    <Option value="XR">XR（值机取消）</Option>
                                    <Option value="CL">CL（订座取消）</Option>
                                    <Option value="SB">SB（候补）</Option>
                                    <Option value="DL">DL（拉下）</Option>
                                </Select>
                            )}
                        </Form.Item>
                    </Col>
                </Row>
                <Row gutter={16}>
                    <Col md={3}></Col>
                    <Col md={5}>
                        <Form.Item label="">
                            {getFieldDecorator('cplk', {
                                initialValue: ["Y"]
                            })(
                                <Checkbox.Group style={{ width: '100%' }}>
                                    <Checkbox value="Y">已出票旅客</Checkbox>
                                </Checkbox.Group>
                            )}
                        </Form.Item>
                    </Col>
                    <Col md={8}>
                        <Form.Item label="">
                            {getFieldDecorator('cxty', {
                                initialValue: ["Y"]
                            })(
                                <Checkbox.Group style={{ width: '100%' }}>
                                    <Checkbox value="Y">包含已取消旅客</Checkbox>
                                </Checkbox.Group>
                            )}
                        </Form.Item>
                    </Col>
                    <Col md={8}>
                        <Form.Item label=" ">
                            {getFieldDecorator('zjzt', {
                                initialValue: []
                            })(
                                <Row gutter={16}>
                                    <Col lg={8} md={24}>

                                        <Button onClick={() => {
                                            setFalse();
                                            let searchValues = getFieldsValue();
                                            let snapSelectVal = searchValues.hd;
                                            let destFlag = "";
                                            let origFlag = "";
                                            // 不是经停(all,all_b_a) 是经停选择航段（before，after）
                                            if (snapSelectVal === "all" ||
                                                snapSelectVal === "all_b_a" ||
                                                snapSelectVal === "before" ||
                                                snapSelectVal === "after") {
                                                destFlag = flightInfo.dest;
                                                origFlag = flightInfo.orig;
                                            }
                                            // 选择AC段
                                            if (snapSelectVal === "ac") {
                                                destFlag = segmentData.cCode;
                                                origFlag = segmentData.aCode;
                                            }
                                            // 是经停
                                            // 前半段的全部
                                            if (snapSelectVal === "all_before") {
                                                destFlag = "";
                                                origFlag = flightInfo.orig;
                                            }
                                            // 后半段的全部
                                            if (snapSelectVal === "all_after") {
                                                destFlag = flightInfo.dest;
                                                origFlag = "";
                                            }
                                            let obj = {
                                                dest: destFlag, //到达航站
                                                orig: origFlag, //起始航班
                                                keySearch: searchValues.keySearch,
                                                passengerName: searchValues.paxName,
                                                flightStartDate: flightInfo.flightDate,
                                                flightEndDate: flightInfo.flightDate,
                                                isCancel: searchValues.cxty.length ? "" : "N",
                                                isPrintTktNo: searchValues.cplk.length ? "Y" : "N",
                                                flightStart: searchValues.tktStartDate ? moment(searchValues.tktStartDate).format('YYYY-MM-DD HH:mm') : '',
                                                flightEnd: searchValues.tktEndDate ? moment(searchValues.tktEndDate).format('YYYY-MM-DD HH:mm') : '',
                                                ticketBeginDate: searchValues.tktStartDate ? moment(searchValues.tktStartDate).format('YYYY-MM-DD HH:mm') : '',
                                                ticketEndDate: searchValues.tktEndDate ? moment(searchValues.tktEndDate).format('YYYY-MM-DD HH:mm') : '',
                                                checkStatus: searchValues.checkStatus
                                            };
                                            obj = { ...flightInfo, ...obj }
                                            queryPassengerMaintenance(obj);
                                        }} style={{ marginRight: "20px" }} type="primary">查询</Button>
                                    </Col>
                                    <Col lg={8} md={24}>
                                        <Button onClick={() => {
                                            setFalse();
                                            resetFields()
                                            let searchValues = getFieldsValue();
                                            let snapSelectVal = searchValues.hd;
                                            let destFlag = "";
                                            let origFlag = "";
                                            // 不是经停(all,all_b_a) 是经停选择航段（before，after）
                                            if (snapSelectVal === "all" ||
                                                snapSelectVal === "all_b_a" ||
                                                snapSelectVal === "before" ||
                                                snapSelectVal === "after") {
                                                destFlag = flightInfo.dest;
                                                origFlag = flightInfo.orig;
                                            }
                                            // 选择AC段
                                            if (snapSelectVal === "ac") {
                                                destFlag = segmentData.cCode;
                                                origFlag = segmentData.aCode;
                                            }
                                            // 是经停
                                            // 前半段的全部
                                            if (snapSelectVal === "all_before") {
                                                destFlag = "";
                                                origFlag = flightInfo.orig;
                                            }
                                            // 后半段的全部
                                            if (snapSelectVal === "all_after") {
                                                destFlag = flightInfo.dest;
                                                origFlag = "";
                                            }
                                            let obj = {
                                                dest: destFlag, //到达航站
                                                orig: origFlag, //起始航班
                                                keySearch: searchValues.keySearch,
                                                paxName: searchValues.paxName,
                                                flightStartDate: flightInfo.flightDate,
                                                flightEndDate: flightInfo.flightDate,
                                                isCancel: searchValues.cxty.length ? "" : "N",
                                                isPrintTktNo: searchValues.cplk.length ? "Y" : "N",
                                                tktStartDate: searchValues.tktStartDate ? moment(searchValues.tktStartDate).format('YYYY-MM-DD HH:mm') : '',
                                                tktEndDate: searchValues.tktEndDate ? moment(searchValues.tktEndDate).format('YYYY-MM-DD HH:mm') : '',
                                                checkStatus: searchValues.checkStatus
                                            };
                                            obj = { ...flightInfo, ...obj }
                                            queryPassengerMaintenance(obj);
                                        }} >重置</Button>
                                    </Col>
                                </Row>
                            )}
                        </Form.Item>
                    </Col>
                </Row>
            </Form>
            <div className={style.personOption}>
                <span onClick={() => { setTrue(); saveAllPassengers(tableSelected) }}>{`已选旅客${checkedMans}人`}</span>
                <span onClick={() => { setFalse(); saveAllPassengers(passengerDataTable) }}>{`全部旅客${allMans}人`}</span>
            </div>
            <Table
                columns={columns}
                dataSource={allPassengers}
                bordered
                rowSelection={{
                    selectedRowKeys,
                    onChange: rowSelection,
                    onSelect: rowOnSelect,
                    onSelectAll: rowOnSelectAll,
                }}
                pagination={false}
                scroll={{ y: 400, x: 700 }}
                rowKey="idx"
                size="small"
            />
            <div className={style.footerToolbar}>
                <Button onClick={submitData} style={{ marginRight: "30px" }} type="primary">确定</Button>
                <Button onClick={() => { handleModalVisible(false) }}>取消</Button>
            </div>
            <IndemnityCountTable {...{ countData, handleModalCount, createModalVisible, passengerName }} />
        </Fragment>
    )
}

export default Form.create()(AddPassenger);